//接口函数文件,统一存放接口函数
//导入axios模块
import axios from 'axios'
import router from '../router'
import {Toast,Dialog } from 'vant';

//设置全局的基准url
// axios.defaults.baseURL = 'http://127.0.0.1:3000/';
axios.defaults.baseURL = 'http://150.158.107.125/api/';

// 设置请求拦截器
axios.interceptors.request.use(config => {
  //设置请求头
  if(!config.headers.Authorization&& localStorage.getItem('token')){
    config.headers.Authorization = localStorage.getItem('token');
  }
  
  return config
})

//设置响应拦截器
axios.interceptors.response.use((res) => {
  const {
    msg,
    code
  } = res.data;

  //token信息过期或错误，跳转到登录
  if(msg && code === 401) {
    return router.push({name: 'login'});
  }

  //请求失败提示信息
  if (msg && code != 200 && !router.currentRoute.name.includes('index')) {
    Toast.fail(msg);
    return false
  }
  
  
  return res.data;
});

export default {
    // 登录验证
    async auth(){
        let token = localStorage.getItem('token')
        if(!token){
          try{
            const res = await Dialog.confirm({
              message: '请先登录!'
            })
            res && router.push({name: 'login'}); 
            
          }catch(e){
            return false
          }
        }else{
          return true
        }
    },
    // post
    async login(params){
        return await axios.post('login',params)
    },
    async register(params){
        return await axios.post('register',params)
    },
    async postComment(params){
        return await axios.post(`post_comment`,params)
    },
    async postEditUserinfo(params){
        return await axios.post(`user/info`,params)

    },
    async uploads(params){
        return await axios.post('uploads',params)
    },
    // get
    async getCates(){
        return await axios.get("news/cates")
    },
    async getNews(params){ 
        return await axios.get("news",{params})
    },
    async getNewsDetail(id){
        return await axios.get(`news/${id}`)
    },
    async getPostComment(id){
        return await axios.get(`post_comment/${id}`)
    },
    async getPostStar(id){
        return await axios.get(`post_star/${id}`)
    },
    async getPostLike(id){
        return await axios.get(`post_like/${id}`)
    },
    async getUserinfo(){
        return await axios.get("user/info")
    },
    async getMyLike(){
      return await axios.get("user_like")
    },
    async getMyComments(params){
      return await axios.get("user_comments",{params})
    },
    async logout(){
      return await axios.get("logout")
    },
    // delete
    async delPostStar(id){
        return await axios.delete(`post_star/${id}`)
    },
    async delPostLike(id){
        return await axios.delete(`post_like/${id}`)
    }
    
}
